import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		
		if user:
			self.response.out.write("""
      <html>
        <body>
          <form id="syncForm" action="/sync" enctype="multipart/form-data"  method="post">
            <div><textarea name="content" id="contentArea" rows="3" cols="60" ></textarea></div>
            <div><input type="file" name="profile"/><</div>
            <div><input type="submit" value="Sync"></div>
          </form>      
        </body>
      </html>""")
		else:
			self.redirect(users.create_login_url(self.request.uri))
			
class Sync(webapp.RequestHandler):
	def post(self):
		user = users.get_current_user()
		
		profile = self.request.get("profile")
		if user:
			data = UserData( key_name = user.nickname(),
											 owner = user,
											 content = self.request.get("content"),
											 profile = db.Blob(profile)
										 )
			data.put()
			self.response.out.write("Successful Database Write of ")
			self.response.out.write( data.content )
		else:
			self.redirect(users.create_login_url(self.request.uri))
			
class Print(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		
		if user:
			data = UserData.get_by_key_name( user.nickname() )
			self.response.out.write( data.owner.nickname() )
			self.response.out.write( " wrote \"" )
			self.response.out.write( data.content )
			self.response.out.write( "\"" )
		else:
			self.redirect(users.create_login_url(self.request.uri))
					
class Profile(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()

		if user:
			data = UserData.get_by_key_name( user.nickname() )
			self.response.headers['Content-Type'] = "application/x-7z-Compressed"
			self.response.out.write( data.profile )
		else:
			self.redirect(users.create_login_url(self.request.uri))

class UserData(db.Model):
	owner = db.UserProperty()
	content = db.TextProperty()
	created = db.DateTimeProperty(auto_now_add=True)
	profile = db.BlobProperty()

class User_Info(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		
		if user:
			self.response.headers['Content-Type'] = 'text/plain'
			self.response.out.write('Hello, webapp World! And Hello ')
			self.response.out.write( user.nickname() )
		else:
			self.redirect(users.create_login_url(self.request.uri))


def main():
	application = webapp.WSGIApplication(
																			 [('/', MainPage),
																			  ('/user', User_Info),
																			  ('/print', Print),
																			  ('/sync', Sync),
																			  ('/profile.7z', Profile)],
																			 debug=True)
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
	main()
